from PyQt5.QtWidgets import *
from myutil import globalvar as gl, logs
from ui.buy_jhm_form import Ui_Frame as buy_jhm_Frame


class buy_jhm_form(QFrame, buy_jhm_Frame):
    def __init__(self, parent=None):
        super(buy_jhm_form, self).__init__(parent)
        self.setupUi(self)

        self.init_app()

        self.check_jhm_pushButton.clicked.connect(self.check_jhm_event)

    def init_app(self):
        self.tishi_label.setVisible(False)
        try:
            jhm = 'abc'
            mysql = gl.get_value("mysql_diver")
            res = mysql.get_find_list("select `free_counts` from `jhm` where `jhm`='{}'".format(jhm))
            self.jhm_nums_label.setText(str(res[0]["free_counts"]))
            if res[0]["free_counts"] == 0 :
                self.tishi_label.setVisible(True)
        except:
            self.tishi_label.setVisible(True)
            self.jhm_nums_label.setText("未知错误")

    def check_jhm_event(self):
        jhm = self.jhm_lineEdit.text()
        try:
            mysql = gl.get_value("mysql_diver")
            res = mysql.get_find_list("select `free_counts` from jhm where `jhm`='{}'".format(jhm))
            if res[0]["free_counts"] <= 0:
                QMessageBox.information(self, '信息', '当前激活码次数已经用完，请重试或者换一个激活码', QMessageBox.Yes, QMessageBox.Yes)
                return 0
            xjxx_dict = gl.get_value("xjxx_dict")
            user_num = xjxx_dict["学号"]
            mysql.add_one("INSERT INTO jhm_user(`jhm_uaer_xuehao`) VALUES (%s);",
                          [user_num])

            mysql.update_or_delete_one("update jhm set free_counts = free_counts-1 where jhm='{}';".format(jhm))

            self.close()
        except:
            QMessageBox.information(self, '信息', '当前激活码不可用，请重试或者换一个激活码', QMessageBox.Yes, QMessageBox.Yes)
            logs.logs_print("当前激活码不可用，请重试或者换一个激活码")
            self.label.setText("当前激活码不可用，请重试或者换一个激活码")
